from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_cors import CORS
import os
import re
from models import db, User, Teacher, UserType
from dotenv import load_dotenv

import os
from dotenv import load_dotenv
# Load environment variables from .env file in the same directory
env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.env'))
load_dotenv(dotenv_path=env_path)

# 初始化Flask应用
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')  # Configure JWT secret key
jwt = JWTManager(app)

# 配置CORS，允许前端跨域请求
CORS(app, resources={r"/api/*": {"origins": "*"}})

# 初始化JWT
jwt = JWTManager(app)

# 根路由-API文档
@app.route('/')
def api_root():
    return jsonify({
        'status': 'success',
        'message': 'Grade System API is running',
        'endpoints': {
            'register': 'POST /api/register',
            'login': 'POST /api/login',
            'userinfo': 'GET /api/userinfo (JWT required)'
        }
    }), 200

# 配置数据库连接
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URI')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化数据库
db.init_app(app)

# 密码强度验证函数
def validate_password(password):
    if len(password) < 8:
        return False
    # 必须包含大小写字母和数字
    if not re.match(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$', password):
        return False
    return True

# 注册API
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['username', 'password', 'user_type']
    for field in required_fields:
        if field not in data:
            return jsonify({'status_code': 400, 'message': f'Missing required field: {field}'}), 400
    
    username = data['username']
    password = data['password']
    user_type = data['user_type']
    subject = data.get('subject')
    
    # 验证用户类型
    if user_type not in ['admin', 'teacher']:
        return jsonify({'status_code': 400, 'message': 'Invalid user_type. Must be admin or teacher'}), 400
    
    # 教师必须提供subject
    if user_type == 'teacher' and not subject:
        return jsonify({'status_code': 400, 'message': 'Teacher must provide subject'}), 400
    
    # 验证密码强度
    if not validate_password(password):
        return jsonify({
            'status_code': 400,
            'message': 'Password must be at least 8 characters and include uppercase, lowercase and number'
        }), 400
    
    # 检查用户名是否已存在
    if User.query.filter_by(username=username).first():
        return jsonify({'status_code': 409, 'message': 'Username already exists'}), 409
    
    try:
        # 创建新用户
        new_user = User(
            username=username,
            user_type=UserType[user_type.upper()]
        )
        new_user.set_password(password)
        db.session.add(new_user)
        db.session.flush()  # 获取新用户ID但不提交事务
        
        # 如果是教师，创建教师信息
        if user_type == 'teacher':
            teacher = Teacher(
                user_id=new_user.id,
                subject=subject,
                full_name=data.get('full_name', '')
            )
            db.session.add(teacher)
        
        db.session.commit()
        return jsonify({'status_code': 201, 'message': 'User registered successfully'}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'status_code': 500, 'message': f'Database error: {str(e)}'}), 500

# 登录API
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    
    if not data or not data.get('username') or not data.get('password'):
        return jsonify({'status_code': 400, 'message': 'Missing username or password'}), 400
    
    user = User.query.filter_by(username=data['username']).first()
    
    if not user or not user.check_password(data['password']):
        return jsonify({'status_code': 401, 'message': 'Invalid credentials'}), 401
    
    # 创建JWT令牌
    access_token = create_access_token(identity=user.id)
    
    # 准备响应数据
    response_data = {
        'token': access_token,
        'user_type': user.user_type.value
    }
    
    # 如果是教师，添加学科信息
    if user.user_type == UserType.TEACHER and user.teacher:
        response_data['subject'] = user.teacher.subject
    
    return jsonify(response_data), 200

# 用户信息API
@app.route('/api/userinfo', methods=['GET'])
@jwt_required()
def get_userinfo():
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'status_code': 404, 'message': 'User not found'}), 404
    
    user_data = {
        'id': user.id,
        'username': user.username,
          'user_type': user.user_type.value
      }
    
    # 如果是教师，添加教师信息
    if user.user_type == UserType.TEACHER and user.teacher:
        user_data['subject'] = user.teacher.subject
        user_data['full_name'] = user.teacher.full_name
    
    return jsonify(user_data), 200

# 创建数据库表
with app.app_context():
    db.create_all()

app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')
if __name__ == '__main__':
    app.run(debug=True)
    app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')